package com.shawn.example.mvvmdemo.login.viewmodule

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.jetpack.mvvm.lib.base.utils.AppCommon
import com.jetpack.mvvm.lib.net.module.HttpApiResult
import com.shawn.example.mvvmdemo.login.repository.RegisterLoginRepository
import com.shawn.example.mvvmdemo.login.vo.UserInfoVO
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class LoginRegisterVM @Inject constructor(val app: Application) : AndroidViewModel(app) {
    companion object {
        private const val TAG = "LoginRegisterVM"
    }

    @Inject
    lateinit var registerRepo: RegisterLoginRepository
    private val _userInfoLiveData: MutableLiveData<UserInfoVO> = MutableLiveData()
    val userInfoLiveData: LiveData<UserInfoVO> = _userInfoLiveData

    fun login(account: String, pwd: String) = viewModelScope.launch {
        withContext(Dispatchers.IO) {
            when (val data = registerRepo.loginWanApp(account, pwd)) {
                is HttpApiResult.Success -> {
                    Log.i(TAG, "${Gson().toJson(data.value)}")
                    Log.i(TAG, "success ${data.value.nickname}")
                    registerRepo.cacheLoginUserData(data.value)
//                    AppCommon.isUserLogin = true
                    _userInfoLiveData.postValue(
                        UserInfoVO(
                            nickName = data.value.nickname ?: "",
                            token = data.value.token ?: "",
                            userName = data.value.publicName ?: "",
                            id = data.value.id ?: 0
                        )
                    )
                }
                else -> {
                    Log.i(TAG, "else #########")
                }
            }

        }
    }
//        registerRepo.loginWanAndroid(account, pwd)
//            .map {
//                Log.e(TAG, "map")
//                it.data
//            }
//            .flowOn(Dispatchers.IO)
//            .catch {
//                Log.e(TAG, "catch")
//                Log.e(TAG, "error message: " + it.message, it)
//            }
//            .collectLatest {
//                Log.e(TAG, "collect")
//                Log.e(TAG, Gson().toJson(it))
//            }

}